package com.dap.core.container;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

import com.alibaba.citrus.springext.support.context.AbstractXmlApplicationContext;
import com.dap.core.config.BootstrapConfigUtil;
import com.dap.core.config.ConfigSvrResource;

public class DapXmlApplicationContext extends AbstractXmlApplicationContext {
    public static final String CONFIGSVR_URL_PREFIX = "configsvr:";
    private Resource[] configResources;


    public DapXmlApplicationContext(String... locations) throws BeansException {
        setConfigLocations(locations);

        setParentResolvableDependenciesAccessible(false);
        refresh();
    }


    public DapXmlApplicationContext(ApplicationContext parentContext, String... locations) throws BeansException {
        super(parentContext);

        setConfigLocations(locations);

        setParentResolvableDependenciesAccessible(false);
        refresh();
    }


    @Override
    protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
        // TODO Auto-generated method stub
        super.customizeBeanFactory(beanFactory);
        beanFactory.setAllowBeanDefinitionOverriding(false);
    }


    public void setConfigResource(Resource... configResources) {
        this.configResources = configResources;
    }


    public void setConfigResource(String... locations) {
        Resource[] resources = new ClassPathResource[locations.length];
        for (int i = 0; i < locations.length; i++) {
            resources[i] = new ClassPathResource(locations[i]);
        }
        this.configResources = resources;
    }


    @Override
    protected Resource[] getConfigResources() {
        return this.configResources;
    }


    @Override
    public Resource getResource(String location) {
        Assert.notNull(location, "Location must not be null");
        if (location.startsWith(CONFIGSVR_URL_PREFIX)) {
            location = location.substring("classpath:".length());
            if (BootstrapConfigUtil.isTrue(BootstrapConfigUtil.CONFIG_SERVER_ENABLE)) {
                try {
                    return new ConfigSvrResource(location);
                } catch (Exception e) {
                    throw new RuntimeException("Could not get config " + location + " from config server!");
                }
            }
            if (location.endsWith("#")) {
                location = location.substring(0, location.length() - 1);
            }
            return new ClassPathResource(location, getClassLoader());
        }
        return super.getResource(location);
    }
}
